﻿Partial Public Class PurchaseOrderExplorer
    Public aProductDataRow As DataRow

    ''' <summary>
    ''' This will process the new Po creation
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    'Private Sub InitnewMasterRow(sender As Object, e As InitNewRowEventArgs)
    '    Dim view As GridView = DirectCast(sender, GridView)
    '    Dim row As DataRow = view.GetFocusedDataRow()
    '    Using plPO As SystemBoxSDK.PL.CRMSDK.PurchaseOrderDetail_PL = New SystemBoxSDK.PL.CRMSDK.PurchaseOrderDetail_PL()
    '        plPO.NewRecord(row)

    '    End Using
    'End Sub


    Public Overridable Sub InitNewRow(sender As Object, e As InitNewRowEventArgs)
        Dim view As GridView = DirectCast(sender, GridView)
        Dim row As DataRow = view.GetFocusedDataRow()

        Select Case row.Table.TableName
            Case "PurchaseOrderDetail_LotTran"
                aLotTransactionHelper.PrepareColumnForReceipt(view)
                Using lotTran As SystemBoxSDK.PL.MESSDK.LotTransaction_PL = New SystemBoxSDK.PL.MESSDK.LotTransaction_PL()
                    lotTran.NewRecord(row)
                    row("TranTypeID_FK") = IdRepository.APP_TRAN_RCPT
                    row("StatusID_FK") = IdRepository.APP_TRANSTATUS_PDG
                    row("TranDate") = Date.Today
                    row("LotTypeId_FK") = IdRepository.APP_LOTTYPELIST_BUY
                    'etc...
                End Using
            Case "PurchaseOrderDetails", "PurchaseOrderDetailGrid"
                Using plPO As SystemBoxSDK.PL.CRMSDK.PurchaseOrderDetail_PL = New SystemBoxSDK.PL.CRMSDK.PurchaseOrderDetail_PL()
                    plPO.NewRecord(row)

                End Using
            Case Else
        End Select

    End Sub


    ''' <summary>
    ''' Process curent Detail Record to set default value
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <param name="index"></param>
    ''' <remarks></remarks>
    Public Overridable Sub ProcessRow(ByVal sender As Object, ByVal e As Views.Base.ValidateRowEventArgs, ByVal index As Integer)
        ' Dim row As DataRow = DirectCast(e.Row, DataRowView).Row
        Dim view As GridView = CType(sender, GridView)
        Dim row As DataRow = view.GetFocusedDataRow()

        If row IsNot Nothing Then
            Select Case row.Table.TableName
                Case "PurchaseOrderDetail_LotTran"
                    'Dim parentview As GridView = CType(view.ParentView, GridView)
                    Dim parentrow As DataRow = CType(view.ParentView, GridView).GetFocusedDataRow
                    aLotTransactionHelper.AssignDefaultValueForRcpt(row)

                Case Else
            End Select
        End If

    End Sub


    Public Overridable Sub ProcessCurrentDetailRecord(ByVal sender As Object, ByVal e As Views.Base.ValidateRowEventArgs, ByVal index As Integer)
        Dim row As DataRow = DirectCast(e.Row, DataRowView).Row
        If row IsNot Nothing Then
            '
            Select Case row.Table.TableName
                Case "InventoryBatchsTransaction"
                    '
                    ' On ne peut pas modifier de transaction release ou Transmitted
                    If Not IsDBNull(row("StatusID_FK")) AndAlso (DirectCast(row("StatusID_FK"), Guid) = IdRepository.APP_TRANSTATUS_REL Or DirectCast(row("StatusID_FK"), Guid) = IdRepository.APP_TRANSTATUS_TRANS) Then
                        Return
                    End If
                    '
                    If Not IsDBNull(row("TranTypeID_FK")) Then
                        Select Case DirectCast(row("TranTypeID_FK"), Guid)
                            Case IdRepository.APP_TRAN_ADJMNT, IdRepository.APP_TRAN_RTRNTOSTOCK
                                aLotTransactionHelper.AssignDefaultValueForAdjustement(row)
                            Case IdRepository.APP_TRAN_PHYCNT
                                aLotTransactionHelper.AssignDefaultValueForPhysCount(row)
                            Case IdRepository.APP_TRAN_PHYCNTINV
                                aLotTransactionHelper.AssignDefaultValueForPhysInv(row)
                            Case IdRepository.APP_TRAN_RCPT
                                aLotTransactionHelper.AssignDefaultValueForRcpt(row)
                            Case IdRepository.APP_TRAN_TRNFER
                                aLotTransactionHelper.AssignDefaultValueForTrsf(row)
                            Case IdRepository.APP_TRAN_SALES
                                aLotTransactionHelper.AssignDefaultValueForSales(row)
                            Case Else
                        End Select
                    End If
            End Select
        End If
    End Sub
    ''' <summary>
    ''' Validation for Rows of what ever levels
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Public Overridable Sub ValidateRow(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs)
        Dim row As DataRow = CType(e.Row, DataRowView).Row
        Select Case row.Table.TableName
            Case "PurchaseOrderDetail_LotTran"
                Using plLotTran As SystemBoxSDK.PL.MESSDK.LotTransaction_PL = New SystemBoxSDK.PL.MESSDK.LotTransaction_PL()
                    plLotTran.ValidateRow(row)
                End Using
            Case "PurchaseOrderDetails", "PurchaseOrderDetailGrid"
                Using plPO As SystemBoxSDK.PL.CRMSDK.PurchaseOrderDetail_PL = New SystemBoxSDK.PL.CRMSDK.PurchaseOrderDetail_PL()
                    plPO.ValidateRow(row)
                End Using
            Case "PurchaseOrder"
                Using plPO As SystemBoxSDK.PL.CRMSDK.PurchaseOrder_PL = New SystemBoxSDK.PL.CRMSDK.PurchaseOrder_PL()
                    plPO.ValidateRow(row)
                End Using
            Case Else
        End Select
    End Sub


    Private Sub RecalcTax2012(ByVal sender As Object, ByVal e As EventArgs)
        Dim aDataRow As DataRow = CType(CType(sender, DXMenuItem).Tag, DataRow)
        Dim PurchaseOrderID As Guid = CType(aDataRow("PurchaseOrderID"), Guid)
        Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing
        Try
            sqlcmd = MetaQuery.GetSPCmdByMetaName("ReCalcTax")
            sqlcmd.Parameters("@PurchaseOrderID").Value = PurchaseOrderID
            sqlcmd.Parameters("@Methode").Value = 3
            sqlcmd.ExecuteNonQuery()
            MessageWindow.ShowMessage("Re-Calcul Complété / Ré-imprimer le PO", MsgBoxStyle.Information)
        Catch ex As Exception
            Throw
        Finally
            If sqlcmd IsNot Nothing Then
                sqlcmd.Connection.Close()
                sqlcmd.Dispose()
            End If
        End Try
    End Sub

    Public Overridable Sub MenuPrintPurchaseOrder(ByVal sender As Object, ByVal e As EventArgs)
        Me.Cursor = Cursors.WaitCursor

        Dim aDataRow As DataRow = CType(CType(sender, DXMenuItem).Tag, DataRow)
        Dim PurchaseOrderID As Guid = CType(aDataRow("PurchaseOrderID"), Guid)

        Dim queryName As String = "RptPODetail"
        Dim reportName As String = "PurchaseOrderReport"

        Using mquery As MetaQuery = MetaQuery.GetMetaQueryByName(queryName)
            If mquery IsNot Nothing Then
                Using report As DevExpress.XtraReports.UI.XtraReport = SCIEF.ActiveFramework.CommonExt.RptNotification.GetReportFromDB(reportName)
                    If report IsNot Nothing Then

                        mquery.SQLWhere = mquery.SQLWhere + String.Format("POD.PurchaseOrderID_FK = '{0}'", PurchaseOrderID)

                        mquery.FillResultQuery()
                        report.DataSource = mquery.ResultQuery
                        report.ShowPreviewDialog()

                        'Dim aFrm As Form = New ReportPrintForm() With {.Text = "Print Invoice", .RptPrintingSystem = report.PrintingSystem}
                        'aFrm.Show()
                    Else
                        Console.WriteLine(String.Format("{0}, Not Found in Report Definition. Notification abord", reportName))
                    End If
                End Using
            Else
                Console.WriteLine(String.Format("{0}, Not Found in MetaCommand. Notification abord", queryName))
            End If
        End Using

        Me.Cursor = Cursors.Default
    End Sub

    Public Overridable Sub InitGridActionOption(ByVal aGrid As GridExtPL)
        Dim action As ActionOption
        'HOWTO : Howto Translate...
        Dim NotRelease As String = DeskTopManager.GetMessage("CONNECT")

        action = New ActionOption("Process", "ACT_xxxxx", "Create Receiving Transactions", AddressOf CreatePOTrans, True, True)
        aGrid.GridActionOptionList.Add(action)


    End Sub



    Public Overridable Sub DetailCustomRowCellEditForEditing(ByVal sender As Object, ByVal e As CustomRowCellEditEventArgs)
        Dim aDetailview As GridView = DirectCast(sender, GridView)
        Dim aParentview As GridView = DirectCast(aDetailview.ParentView, GridView)
        Dim parentrow As DataRow = aParentview.GetFocusedDataRow
        Dim aLotTranRow As DataRow = aDetailview.GetFocusedDataRow()
        Dim aEdit As RepositoryItemGridLookUpEdit
        Dim aProductId As Guid
        Dim sqlWhere As String

        Select Case aDetailview.Tag.ToString
            Case "PurchaseOrderDetail_LotTran"
                If e.Column.FieldName = "LotID_FK" Then
                    aProductId = CType(If(IsDBNull(parentrow("ProductID_FK")), Guid.Empty, parentrow("ProductID_FK")), Guid)

                    sqlWhere = String.Format("PrdId_FK = '{0}'", aProductId.ToString)
                    aEdit = LOVBuilder("LOV_Lot", sqlWhere, Nothing, Nothing)

                    aEdit.Name = "LOV_Lot"
                    aDetailview.GridControl.RepositoryItems.Add(aEdit)
                    e.RepositoryItem = aEdit
                End If
                If e.Column.FieldName = "PrdId_FK" Then
                    aProductId = CType(If(IsDBNull(parentrow("ProductID_FK")), Guid.Empty, parentrow("ProductID_FK")), Guid)

                    sqlWhere = String.Format("PrdId = '{0}'", aProductId.ToString)
                    aEdit = LOVBuilder("LOV_Product", sqlWhere, Nothing, Nothing)

                    aEdit.Name = "LOV_Product"
                    aDetailview.GridControl.RepositoryItems.Add(aEdit)
                    e.RepositoryItem = aEdit
                End If
            Case Else
        End Select


    End Sub

    Public Overridable Sub DetailCellValueChanged(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs)
        Dim view As GridView = DirectCast(sender, GridView)
        Dim row As DataRow = view.GetFocusedDataRow()

        If row IsNot Nothing Then
            If row.Table.TableName = "PurchaseOrderDetail_LotTran" Then

                If e.Column.FieldName = "PrdId_FK" Then
                    aLotTransactionHelper.InitRow(row)
                    row("LotID_FK") = DBNull.Value
                    aLotTransactionHelper.AssignDefaultValue(row)
                    aLotTransactionHelper.AssignViewRowProperty(view, row)
                End If
                If e.Column.FieldName = "LotID_FK" Then
                    aLotTransactionHelper.InitRow(row)
                    row("PrdId_FK") = DBNull.Value
                    aLotTransactionHelper.AssignDefaultValue(row)
                    aLotTransactionHelper.AssignViewRowProperty(view, row)
                End If


            End If
        End If

    End Sub



    ''' <summary>
    ''' Faire le save sur le changement d'une faleur sur une row
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Public Overridable Sub RowNotify(sender As Object, e As RowObjectEventArgs)
        Dim aDataRow As DataRow = TryCast(e.Row, DataRowView).Row
        If aDataRow IsNot Nothing Then
            If aDataRow.IsColumnChanged("StatusID_FK") Then
                Me.aGridControl.SaveCommand()
                'MessageWindow.ShowMessage("Notify on Row:" + aDataRow.Table.TableName)
            End If
        End If
    End Sub



    ''
    ''
    '' OutStandingIssues: A faire en Helper - aleblanc 2011-10-26
    ''
    ''
    Protected formatType As DevExpress.Utils.FormatType
    ''' <summary>
    ''' use to Build a LOV for our GRID
    ''' </summary>
    ''' <param name="queryName"></param>
    ''' <param name="sqlWhere"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Protected Function LOVBuilder(ByVal queryName As String, ByVal sqlWhere As String, ByVal sqlFrom As String, ByVal filter As String) As RepositoryItemGridLookUpEdit
        Dim aEdit As RepositoryItemGridLookUpEdit
        Dim colVisible As Boolean
        Dim hideCol As Boolean
        Dim colname As String
        Dim Column As DevExpress.XtraGrid.Columns.GridColumn
        Dim view As Views.Base.ColumnView

        Using mq As MetaQuery = MetaQuery.GetMetaQueryByName(queryName)
            If Not String.IsNullOrWhiteSpace(sqlWhere) Then
                mq.SQLWhere = sqlWhere
            End If
            '

            'ICI Le DataField filter appliquer quand on a la securité
            If Not String.IsNullOrWhiteSpace(sqlFrom) Then
                mq.SQLFrom = String.Concat(mq.SQLFrom, sqlFrom)
            End If

            If Not String.IsNullOrWhiteSpace(filter) Then
                mq.SQLWhere = String.Concat(mq.SQLWhere, filter)
            End If
            '
            mq.FillResultQuery()
            aEdit = New RepositoryItemGridLookUpEdit() With {.DataSource = mq.ResultQuery, .DisplayMember = mq.ResultQuery.Columns(CommonExt.Base.AppManager.ApplicationOption.DescriptionColumnIndex).ToString, .ValueMember = mq.GUIDField, .PopupFormSize = New Size(800, 300), .NullText = "(none)"}
            aEdit.View.HorzScrollVisibility = Views.Base.ScrollVisibility.Always
            aEdit.View.OptionsView.ColumnAutoWidth = False
            aEdit.View.OptionsView.ShowAutoFilterRow = True
            aEdit.View.OptionsBehavior.ReadOnly = True
            view = aEdit.View
            view.Columns.Clear()
            For Each row As DataRow In mq.MetaColumns.Rows
                colname = row("ColumnName").ToString
                hideCol = False
                If AppManager.ApplicationOption.DescriptionColumnIndex = 2 Then
                    If colname.EndsWith("_ALT") Then
                        hideCol = True
                    End If
                Else
                    If colname.EndsWith("_PRM") Then
                        hideCol = True
                    End If
                End If
                If hideCol = False Then
                    colVisible = CBool(IIf(CInt(row("pVisible")) = 0, False, True))
                    Column = view.Columns.AddField(colname)
                    Column.VisibleIndex = CInt(row("pOrder"))
                    Column.Caption = row("pCaption").ToString
                    Column.Visible = colVisible
                    Column.Width = CInt(row("pWidth"))
                    Column.ToolTip = row("pToolTip").ToString

                    formatType = GetFormatType(row)
                    '
                    Column.DisplayFormat.FormatType = formatType
                    Column.DisplayFormat.FormatString = row("pNumberFormat").ToString
                End If
            Next
            aEdit.DataSource = mq.ResultQuery
            Return aEdit
        End Using
    End Function

    Protected Function GetFormatType(ByVal arow As DataRow) As DevExpress.Utils.FormatType
        If (Not String.IsNullOrEmpty(arow("pNumberFormatID_FK").ToString)) Then
            Select Case CType(arow("pNumberFormatID_FK"), Guid)

                Case CommonExt.Base.IdRepository.META_NUMBERFORMAT_CURRENCY, CommonExt.Base.IdRepository.META_NUMBERFORMAT_GENERALNUMBER, CommonExt.Base.IdRepository.META_NUMBERFORMAT_PERCENT, CommonExt.Base.IdRepository.META_NUMBERFORMAT_STANDARD, CommonExt.Base.IdRepository.META_NUMBERFORMAT_SCIENTIFIC
                    Return DevExpress.Utils.FormatType.Numeric

                Case CommonExt.Base.IdRepository.META_NUMBERFORMAT_GENERALDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_LONGDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_LONGTIME, CommonExt.Base.IdRepository.META_NUMBERFORMAT_MEDIUMDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_MEDIUMTIME, CommonExt.Base.IdRepository.META_NUMBERFORMAT_SHORTDATE, CommonExt.Base.IdRepository.META_NUMBERFORMAT_SHORTTIME
                    Return DevExpress.Utils.FormatType.DateTime

                Case CommonExt.Base.IdRepository.META_NUMBERFORMAT_FORMATEXPR
                    Return DevExpress.Utils.FormatType.Custom

                Case Else
                    Return DevExpress.Utils.FormatType.None
            End Select
        Else
            Return DevExpress.Utils.FormatType.None
        End If
    End Function
    ''
    ''

    Private Sub CreatePOTrans(ByVal sender As Object, ByVal e As EventArgs)
        Dim aDataRow As DataRow = CType(CType(sender, DXMenuItem).Tag, DataRow)
        Dim PurchaseOrderID As Guid = CType(aDataRow("PurchaseOrderID"), Guid)
        Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing
        Try
            sqlcmd = MetaQuery.GetSPCmdByMetaName("bsp_Generate_InventoryBatch_LotTrans")
            sqlcmd.Parameters("@OrderID").Value = PurchaseOrderID
            sqlcmd.ExecuteNonQuery()
            MessageWindow.ShowMessage("Done", MsgBoxStyle.Information)
        Catch ex As Exception
            Throw
        Finally
            If sqlcmd IsNot Nothing Then
                sqlcmd.Connection.Close()
                sqlcmd.Dispose()
            End If
        End Try
    End Sub

End Class
